package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import com.qingcheng.util.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @Author:boy
 * @Date:2019/7/10
 * @description:
 * @ModifiedBy:
 */
@Controller
public class SearchController {
    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String, String> searchMap) throws Exception {
        searchMap = WebUtil.convertCharsetToUTF8(searchMap);
        //处理排序参数
        if (searchMap.get("sort") == null) {
            searchMap.put("sort", "");
        }
        if (searchMap.get("sortOrder") == null) {
            searchMap.put("sortOrder", "DESC");
        }
        Map result = skuSearchService.search(searchMap);
        //处理分页
        Long totalPage = (Long) result.get("totalPage");
        Integer startPage = 1;
        Integer endPage = 5;
        if (searchMap.get("pageNum") == null) {
            searchMap.put("pageNum", "1");
        }
        Integer pageNum = Integer.parseInt(searchMap.get("pageNum"));
        if (totalPage > 5) {
            startPage = pageNum - 2;
            endPage = pageNum + 2;
            if (pageNum - 1 <= 2) {
                startPage = 1;
                endPage = startPage + 4;
            }
            if (totalPage - pageNum <= 2) {
                endPage = totalPage.intValue();
                startPage = endPage - 4;
            }
        }
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("startPage", startPage);
        model.addAttribute("endPage", endPage);

        model.addAttribute("result", result);
        //url处理回传
        StringBuilder url = new StringBuilder("/search.do?");
        for (String key : searchMap.keySet()) {
            url.append("&" + key + "=" + searchMap.get(key));
        }
        model.addAttribute("url", url);
        //回传查询条件
        model.addAttribute("searchMap", searchMap);
        return "search";
    }

}
